package Q5;

import Q4.Client;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;
import Q5.ClientTool;

public class ClientA {

    private static String username;

    public static void main(String[] args) {
        Socket s = null;
        Scanner sc = null;
        PrintStream ps = null;
        BufferedReader br = null;
        try {
            //让用户输入昵称
            System.out.println("请输入你的昵称");
            sc = new Scanner(System.in);
            username = sc.nextLine().strip();

            //连接客户端
            s = new Socket("127.0.0.1", 8888);
            ps = new PrintStream(s.getOutputStream());
            ps.println(username);
            System.out.println("已加入群组");

            //建立本地存储目录
            ClientTool.createLocalStorage(username);
            ClientRead myRunnable = new ClientRead(s, username);
            Thread thread = new Thread(myRunnable);
            thread.start();



            //循环提示用户输入聊天内容，并发送消息和文件给服务器
            while(true) {
                String userInput = sc.next().strip();
                //发送“退出”则退出群聊
                if ("退出".equalsIgnoreCase(userInput)) {
                    System.out.println("退出群聊");
                    break;
                } else if ("发送文件".equalsIgnoreCase(userInput)) {
                    System.out.println("请输入要发送的文件：");
                    String fileName = sc.nextLine().strip();
                    //初始化文件
                    File file = new File("D:/Talk/client" + username + fileName);
                    //拒绝文件夹
                    if (file.isDirectory()) {
                        System.out.println("不支持发送文件夹");
                        continue;
                    }
                    if (file.exists()) {
                        //发送文件到服务器
                        ps.println(userInput);
                        ps.println(fileName);
                        ClientTool.sendFile(file, s);
                    } else {
                        System.out.println("文件不存在");
                    }
                } else if ("下载文件".equalsIgnoreCase(userInput)) {
                    System.out.println("请输入文件名");
                    String fileName = sc.nextLine().strip();
                    ps.println(userInput);
                    ps.println(fileName);
                } else {
                    //发送聊天内容
                    ps.println(userInput);
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ps != null) {
                ps.close();
            }
            if (sc != null) {
                sc.close();
            }
            try {
                if (s != null) {
                    s.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
